import getLastEvent from '../utils/getLastEvent';
import getSelector from '../utils/getSelector';
import getStackLines from '../utils/getStackLines';
import tracker from '../utils/tracker';

export function injectJsError(){
  console.log('injectJsError 正在监控 全局未捕获的JS执行错误、promise错误 以及 js/css脚本加载异常 --- ---');

  //监听全局未捕获的错误
  //1) 监听普通js执行错误
  window.addEventListener('error', (event) => {
    console.log('window.addEventListener ---> on error --->  event:', event);
    const lastEvent = getLastEvent(); //里面有一个属性 ---> path: (7) [input, div.content, div#container, body, html, document, Window]

    //这是一个脚本加载错误
    if(event.target && event.target.src || event.target.href){
      tracker.send({
        kind: 'stability',
        type: 'error',
        errorType: 'resourceError', //js或css资源加载错误
        url: '', //访问的哪个路径
        filename: event.target.src || event.target.href, //哪个文件报错
        tagName: event.target.tagName, //SCRIPT
        selector: getSelector(event.target)
      });
    }else {
      tracker.send({
        kind: 'stability',
        type: 'error',
        errorType: 'jsError', //js执行错误
        url: '', //访问的哪个路径
        message: event.message, //报错信息
        filename: event.filename, //哪个文件报错
        position: `${event.lineno}:${event.colno}`, //多少行多少列
        stack: event.error && getStackLines(event.error.stack), //undefinederrorClick (http://localhost:8080/:18:28)^undefinedHTMLInputElement.onclick (http://localhost:8080/:11:67)
        selector: lastEvent ? getSelector(lastEvent.path) : null //html body div#container div.content input
      });
    }

  }, true/*为true时,才会捕获资源加载错误*/);
  //2) 监听promise错误
  window.addEventListener('unhandledrejection', (event) => {
    console.log('window.addEventListener ---> on unhandledrejection --->  event:', event);

    const lastEvent = getLastEvent();
    let
      message,
      reason = event.reason,
      filename,
      line = 0,
      column = 0,
      stack = '';

    if (typeof event.reason === 'string') { //eject触发的
      message = event.reason;

    }else if(typeof event.reason === 'object'){ //非eject触发的
      if(reason.stack){
        const matchResult = reason.stack.match(/at\s+(.+):(\d+):(\d+)/)
        filename = matchResult[1];
        line = matchResult[2];
        column = matchResult[3];
        stack = getStackLines(reason.stack)
      }
      message = reason.message;
    }

    tracker.send({
      kind: 'stability',
      type: 'error',
      errorType: 'promiseError', //js执行错误
      url: '', //访问的哪个路径
      message, //报错信息
      filename, //哪个文件报错
      position: `${line}:${column}`, //多少行多少列
      stack: stack, //undefinederrorClick (http://localhost:8080/:18:28)^undefinedHTMLInputElement.onclick (http://localhost:8080/:11:67)
      selector: lastEvent ? getSelector(lastEvent.path) : null //html body div#container div.content input
    });

  },true);
}

